package com.itnetwork.DaoImp;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.itnetwork.Entity.Category;
import com.itnetwork.Entity.News;

@Component("newsDaoImp")
public class NewsDaoImp {
	
	//private HibernateTemplate hibernateTemplate;
	private SessionFactory sessionFactory;
	public int getCount(int cid)
	{
		Session session = sessionFactory.getCurrentSession();
		Query q= session.createQuery("select count(*) from News"+
								(cid!=0?" n where n.category.cid ="+cid:""));
		int total=Integer.parseInt(q.uniqueResult().toString());
		return total;
		
	}
	public Category getCategoryById(int id)
	{
		Session session = sessionFactory.getCurrentSession();
		//Category category=(Category) hibernateTemplate.get(Category.class, id);
		Category category = (Category)session.get(Category.class, id);
		return category;
	}
	
	//分页查询，
	public List<News>  getNewsList(int start,int limit,int cid)
	{
		List<News> newslist = new ArrayList<News>();
		
		Session session =sessionFactory.getCurrentSession();
		String hsql = "from News "+(cid!=0?" n  where n.category.cid = "+cid:"");
												//+" limit "+start+","+limit;
		System.out.println(hsql);
		Query query =session.createQuery(hsql)
						.setFirstResult(start)
						.setMaxResults(limit);
		newslist = query.list();
		return newslist;
	}

	//存储单条新闻信息
	public void saveNews(News news)
	{
		Session session =sessionFactory.getCurrentSession();
		session.save(news);
	}
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}



//测试查询语句:from News n where n.category.cid =id
/*	public void testGetNews()
	{
		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();
		tr.begin();
		Query q =session.createQuery("from News n where n.category.cid =13");
		List<News> newslist = q.list();
		System.out.print(newslist.size());
		
		tr.commit();
		session.clear();
		System.out.println(newslist.get(0).getCategory().getCtitle());
		sessionFactory.close();
	}*/
